{% extends 'base.html' %}
{% load static %}

{% block title %}数据上传 - CFS Web System{% endblock %}

{% block extra_css %}
<style>
.upload-area {
    border: 2px dashed #dee2e6;
    border-radius: 8px;
    padding: 40px;
    text-align: center;
    background: #f8f9fa;
    transition: all 0.3s ease;
    cursor: pointer;
}

.upload-area.dragover {
    border-color: #007bff;
    background: #e3f2fd;
}

.upload-area:hover {
    border-color: #007bff;
    background: #f0f8ff;
}

.file-preview {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 10px;
    background: white;
}

.file-item {
    display: flex;
    align-items: center;
    padding: 8px;
    border-bottom: 1px solid #eee;
    transition: background 0.2s;
}

.file-item:hover {
    background: #f8f9fa;
}

.file-item:last-child {
    border-bottom: none;
}

.file-icon {
    width: 24px;
    height: 24px;
    margin-right: 10px;
    flex-shrink: 0;
}

.file-info {
    flex: 1;
    min-width: 0;
}

.file-name {
    font-weight: 500;
    margin-bottom: 2px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.file-size {
    font-size: 0.875rem;
    color: #6c757d;
}

.file-actions {
    display: flex;
    gap: 5px;
}

.template-card {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    cursor: pointer;
    transition: all 0.2s;
}

.template-card:hover {
    border-color: #007bff;
    box-shadow: 0 2px 8px rgba(0,123,255,0.15);
}

.template-card.selected {
    border-color: #007bff;
    background: #f0f8ff;
}

.template-header {
    display: flex;
    justify-content: between;
    align-items: center;
    margin-bottom: 10px;
}

.template-name {
    font-weight: 600;
    color: #333;
}

.template-status {
    font-size: 0.75rem;
    padding: 2px 8px;
    border-radius: 12px;
    font-weight: 500;
}

.template-status.active {
    background: #d4edda;
    color: #155724;
}

.template-status.inactive {
    background: #f8d7da;
    color: #721c24;
}

.template-description {
    color: #6c757d;
    font-size: 0.875rem;
    margin-bottom: 8px;
}

.template-meta {
    display: flex;
    gap: 15px;
    font-size: 0.75rem;
    color: #6c757d;
}

.processing-options {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-top: 20px;
}

.option-group {
    margin-bottom: 20px;
}

.option-group:last-child {
    margin-bottom: 0;
}

.option-label {
    font-weight: 600;
    margin-bottom: 10px;
    color: #333;
}

.progress-container {
    margin-top: 20px;
    display: none;
}

.progress {
    height: 8px;
    border-radius: 4px;
    overflow: hidden;
}

.progress-bar {
    transition: width 0.3s ease;
}

.step-indicator {
    display: flex;
    justify-content: center;
    margin-bottom: 30px;
}

.step {
    display: flex;
    align-items: center;
    color: #6c757d;
}

.step.active {
    color: #007bff;
    font-weight: 600;
}

.step.completed {
    color: #28a745;
}

.step-number {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #e9ecef;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
    font-weight: 600;
}

.step.active .step-number {
    background: #007bff;
    color: white;
}

.step.completed .step-number {
    background: #28a745;
    color: white;
}

.step-connector {
    width: 50px;
    height: 2px;
    background: #e9ecef;
    margin: 0 15px;
}

.step.completed + .step .step-connector {
    background: #28a745;
}

@media (max-width: 768px) {
    .template-meta {
        flex-direction: column;
        gap: 5px;
    }
    
    .step-indicator {
        flex-direction: column;
        gap: 10px;
    }
    
    .step-connector {
        display: none;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 步骤指示器 -->
    <div class="step-indicator">
        <div class="step active" id="step-upload">
            <div class="step-number">1</div>
            <span>上传数据</span>
        </div>
        <div class="step-connector"></div>
        <div class="step" id="step-template">
            <div class="step-number">2</div>
            <span>选择模板</span>
        </div>
        <div class="step-connector"></div>
        <div class="step" id="step-process">
            <div class="step-number">3</div>
            <span>处理配置</span>
        </div>
        <div class="step-connector"></div>
        <div class="step" id="step-confirm">
            <div class="step-number">4</div>
            <span>确认提交</span>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <!-- 步骤1: 数据上传 -->
            <div class="card step-content" id="upload-step">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-upload me-2"></i>数据上传
                    </h5>
                </div>
                <div class="card-body">
                    <div class="upload-area" id="uploadArea">
                        <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                        <h5>拖拽文件到此处或点击选择文件</h5>
                        <p class="text-muted">支持 Excel (.xlsx, .xls), CSV (.csv), TXT (.txt) 格式</p>
                        <p class="text-muted">最大文件大小: 50MB</p>
                        <input type="file" id="fileInput" multiple accept=".xlsx,.xls,.csv,.txt" style="display: none;">
                    </div>
                    
                    <div class="mt-3" id="filePreview" style="display: none;">
                        <h6>已选择的文件:</h6>
                        <div class="file-preview" id="fileList"></div>
                        
                        <!-- 数据源名称选择 -->
                        <div class="mt-3">
                            <h6>数据源配置:</h6>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>提示：</strong>请为每个文件指定对应的数据源名称，这将用于模板处理时的数据源匹配。
                            </div>
                            <div id="sourceNameConfig"></div>
                        </div>
                    </div>
                    
                    <div class="progress-container" id="uploadProgress">
                        <div class="d-flex justify-content-between mb-2">
                            <span>上传进度</span>
                            <span id="progressText">0%</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar" id="progressBar" style="width: 0%"></div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="button" class="btn btn-primary" id="nextToTemplate" disabled>
                        下一步: 选择模板 <i class="fas fa-arrow-right ms-1"></i>
                    </button>
                </div>
            </div>

            <!-- 步骤2: 模板选择 -->
            <div class="card step-content" id="template-step" style="display: none;">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-file-alt me-2"></i>选择处理模板
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <input type="text" class="form-control" id="templateSearch" placeholder="搜索模板...">
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" id="templateFilter">
                                <option value="">所有状态</option>
                                <option value="active">启用</option>
                                <option value="inactive">禁用</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" id="templateSort">
                                <option value="name">按名称排序</option>
                                <option value="created">按创建时间</option>
                                <option value="updated">按更新时间</option>
                            </select>
                        </div>
                    </div>
                    
                    <div id="templateList">
                        <!-- 模板列表将通过JavaScript动态加载 -->
                    </div>
                    
                    <div class="text-center mt-3" id="templateLoading" style="display: none;">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="button" class="btn btn-secondary me-2" id="backToUpload">
                        <i class="fas fa-arrow-left me-1"></i> 上一步
                    </button>
                    <button type="button" class="btn btn-primary" id="nextToProcess" disabled>
                        下一步: 处理配置 <i class="fas fa-arrow-right ms-1"></i>
                    </button>
                </div>
            </div>

            <!-- 步骤3: 处理配置 -->
            <div class="card step-content" id="process-step" style="display: none;">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-cogs me-2"></i>处理配置
                    </h5>
                </div>
                <div class="card-body">
                    <div class="processing-options">
                        <div class="option-group">
                            <div class="option-label">输出格式</div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="outputFormat" id="formatExcel" value="excel" checked>
                                <label class="form-check-label" for="formatExcel">Excel (.xlsx)</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="outputFormat" id="formatCsv" value="csv">
                                <label class="form-check-label" for="formatCsv">CSV (.csv)</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="outputFormat" id="formatTxt" value="txt">
                                <label class="form-check-label" for="formatTxt">文本 (.txt)</label>
                            </div>
                        </div>
                        
                        <div class="option-group">
                            <div class="option-label">处理选项</div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="removeEmptyRows" checked>
                                <label class="form-check-label" for="removeEmptyRows">
                                    移除空行
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="trimWhitespace" checked>
                                <label class="form-check-label" for="trimWhitespace">
                                    去除首尾空格
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="validateData">
                                <label class="form-check-label" for="validateData">
                                    数据验证
                                </label>
                            </div>
                        </div>
                        
                        <div class="option-group">
                            <div class="option-label">任务优先级</div>
                            <select class="form-select" id="taskPriority">
                                <option value="low">低</option>
                                <option value="normal" selected>普通</option>
                                <option value="high">高</option>
                                <option value="urgent">紧急</option>
                            </select>
                        </div>
                        
                        <div class="option-group">
                            <div class="option-label">任务描述</div>
                            <textarea class="form-control" id="taskDescription" rows="3" placeholder="可选：描述此次处理任务的目的或备注"></textarea>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="button" class="btn btn-secondary me-2" id="backToTemplate">
                        <i class="fas fa-arrow-left me-1"></i> 上一步
                    </button>
                    <button type="button" class="btn btn-primary" id="nextToConfirm">
                        下一步: 确认提交 <i class="fas fa-arrow-right ms-1"></i>
                    </button>
                </div>
            </div>

            <!-- 步骤4: 确认提交 -->
            <div class="card step-content" id="confirm-step" style="display: none;">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-check-circle me-2"></i>确认提交
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6>上传文件</h6>
                            <div id="confirmFiles"></div>
                        </div>
                        <div class="col-md-6">
                            <h6>选择模板</h6>
                            <div id="confirmTemplate"></div>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <h6>处理配置</h6>
                    <div id="confirmConfig"></div>
                    
                    <div class="alert alert-info mt-3">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>提示：</strong>提交后将开始处理任务，您可以在任务管理页面查看处理进度和结果。
                    </div>
                </div>
                <div class="card-footer">
                    <button type="button" class="btn btn-secondary me-2" id="backToProcess">
                        <i class="fas fa-arrow-left me-1"></i> 上一步
                    </button>
                    <button type="button" class="btn btn-success" id="submitTask">
                        <i class="fas fa-play me-1"></i> 提交任务
                    </button>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <!-- 侧边栏信息 -->
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-info-circle me-2"></i>使用说明
                    </h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <h6>支持的文件格式</h6>
                        <ul class="list-unstyled">
                            <li><i class="fas fa-file-excel text-success me-2"></i>Excel (.xlsx, .xls)</li>
                            <li><i class="fas fa-file-csv text-info me-2"></i>CSV (.csv)</li>
                            <li><i class="fas fa-file-alt text-secondary me-2"></i>文本 (.txt)</li>
                        </ul>
                    </div>
                    
                    <div class="mb-3">
                        <h6>文件要求</h6>
                        <ul class="list-unstyled text-muted">
                            <li>• 最大文件大小: 50MB</li>
                            <li>• 支持多文件上传</li>
                            <li>• 建议使用UTF-8编码</li>
                        </ul>
                    </div>
                    
                    <div>
                        <h6>处理流程</h6>
                        <ol class="list-unstyled text-muted">
                            <li>1. 上传数据文件</li>
                            <li>2. 选择处理模板</li>
                            <li>3. 配置处理选项</li>
                            <li>4. 提交处理任务</li>
                        </ol>
                    </div>
                </div>
            </div>
            
            <!-- 最近任务 -->
            <div class="card mt-3">
                <div class="card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-history me-2"></i>最近任务
                    </h6>
                </div>
                <div class="card-body">
                    <div id="recentTasks">
                        <!-- 最近任务列表将通过JavaScript动态加载 -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 任务提交成功模态框 -->
<div class="modal fade" id="successModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-check-circle text-success me-2"></i>任务提交成功
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>您的数据处理任务已成功提交！</p>
                <div class="alert alert-success">
                    <strong>任务ID：</strong><span id="taskId"></span>
                </div>
                <p>您可以通过以下方式查看任务进度：</p>
                <ul>
                    <li>在任务管理页面查看详细进度</li>
                    <li>等待邮件通知（如已启用）</li>
                    <li>在仪表板查看任务状态</li>
                </ul>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <a href="{% url 'data_processing:task_list' %}" class="btn btn-primary">查看任务</a>
                <button type="button" class="btn btn-success" id="createNewTask">创建新任务</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 全局变量
    let uploadedFiles = [];
    let selectedTemplate = null;
    let currentStep = 1;
    
    // 初始化
    initializeUpload();
    loadRecentTasks();
    
    // 文件上传初始化
    function initializeUpload() {
        const uploadArea = $('#uploadArea');
        const fileInput = $('#fileInput');
        
        // 点击上传区域
        uploadArea.on('click', function() {
            fileInput.click();
        });
        
        // 文件选择
        fileInput.on('change', function() {
            handleFiles(this.files);
        });
        
        // 拖拽上传
        uploadArea.on('dragover', function(e) {
            e.preventDefault();
            $(this).addClass('dragover');
        });
        
        uploadArea.on('dragleave', function(e) {
            e.preventDefault();
            $(this).removeClass('dragover');
        });
        
        uploadArea.on('drop', function(e) {
            e.preventDefault();
            $(this).removeClass('dragover');
            handleFiles(e.originalEvent.dataTransfer.files);
        });
    }
    
    // 处理文件
    function handleFiles(files) {
        const allowedTypes = ['.xlsx', '.xls', '.csv', '.txt'];
        const maxSize = 50 * 1024 * 1024; // 50MB
        
        Array.from(files).forEach(file => {
            // 检查文件类型
            const fileExt = '.' + file.name.split('.').pop().toLowerCase();
            if (!allowedTypes.includes(fileExt)) {
                showNotification('不支持的文件格式: ' + file.name, 'error');
                return;
            }
            
            // 检查文件大小
            if (file.size > maxSize) {
                showNotification('文件过大: ' + file.name + ' (最大50MB)', 'error');
                return;
            }
            
            // 检查重复
            if (uploadedFiles.find(f => f.name === file.name && f.size === file.size)) {
                showNotification('文件已存在: ' + file.name, 'warning');
                return;
            }
            
            uploadedFiles.push(file);
        });
        
        updateFilePreview();
        updateNextButton();
    }
    
    // 更新文件预览
    function updateFilePreview() {
        const fileList = $('#fileList');
        const filePreview = $('#filePreview');
        const sourceNameConfig = $('#sourceNameConfig');
        
        if (uploadedFiles.length === 0) {
            filePreview.hide();
            return;
        }
        
        filePreview.show();
        fileList.empty();
        sourceNameConfig.empty();
        
        uploadedFiles.forEach((file, index) => {
            const fileItem = $(`
                <div class="file-item" data-index="${index}">
                    <div class="file-icon">
                        <i class="fas ${getFileIcon(file.name)}"></i>
                    </div>
                    <div class="file-info">
                        <div class="file-name">${file.name}</div>
                        <div class="file-size">${formatFileSize(file.size)}</div>
                    </div>
                    <div class="file-actions">
                        <button type="button" class="btn btn-sm btn-outline-danger remove-file" data-index="${index}">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            `);
            
            fileList.append(fileItem);
            
            // 添加数据源名称配置
            const sourceConfigItem = $(`
                <div class="row mb-3 align-items-center" data-file-index="${index}">
                    <div class="col-md-4">
                        <label class="form-label mb-0">
                            <i class="fas ${getFileIcon(file.name)} me-2"></i>
                            ${file.name}
                        </label>
                    </div>
                    <div class="col-md-6">
                        <input type="text" class="form-control source-name-input" 
                               data-file-index="${index}" 
                               placeholder="请输入数据源名称（如：订单数据、客户信息等）"
                               value="${file.sourceName || ''}">
                    </div>
                    <div class="col-md-2">
                        <select class="form-select file-type-select" data-file-index="${index}">
                            <option value="source" ${(!file.fileType || file.fileType === 'source') ? 'selected' : ''}>源文件</option>
                            <option value="template" ${file.fileType === 'template' ? 'selected' : ''}>模板文件</option>
                            <option value="target" ${file.fileType === 'target' ? 'selected' : ''}>目标文件</option>
                            <option value="po" ${file.fileType === 'po' ? 'selected' : ''}>PO文件</option>
                        </select>
                    </div>
                </div>
            `);
            
            sourceNameConfig.append(sourceConfigItem);
        });
    }
    
    // 获取文件图标
    function getFileIcon(filename) {
        const ext = filename.split('.').pop().toLowerCase();
        switch (ext) {
            case 'xlsx':
            case 'xls':
                return 'fa-file-excel text-success';
            case 'csv':
                return 'fa-file-csv text-info';
            case 'txt':
                return 'fa-file-alt text-secondary';
            default:
                return 'fa-file text-muted';
        }
    }
    
    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 移除文件
    $(document).on('click', '.remove-file', function() {
        const index = $(this).data('index');
        uploadedFiles.splice(index, 1);
        updateFilePreview();
        updateNextButton();
    });
    
    // 数据源名称输入变更
    $(document).on('input', '.source-name-input', function() {
        const fileIndex = $(this).data('file-index');
        const sourceName = $(this).val();
        if (uploadedFiles[fileIndex]) {
            uploadedFiles[fileIndex].sourceName = sourceName;
        }
    });
    
    // 文件类型选择变更
    $(document).on('change', '.file-type-select', function() {
        const fileIndex = $(this).data('file-index');
        const fileType = $(this).val();
        if (uploadedFiles[fileIndex]) {
            uploadedFiles[fileIndex].fileType = fileType;
        }
    });
    
    // 更新下一步按钮状态
    function updateNextButton() {
        $('#nextToTemplate').prop('disabled', uploadedFiles.length === 0);
    }
    
    // 步骤导航
    $('#nextToTemplate').on('click', function() {
        if (uploadedFiles.length === 0) {
            showNotification('请先上传文件', 'warning');
            return;
        }
        goToStep(2);
        loadTemplates();
    });
    
    $('#backToUpload').on('click', function() {
        goToStep(1);
    });
    
    $('#nextToProcess').on('click', function() {
        if (!selectedTemplate) {
            showNotification('请选择一个模板', 'warning');
            return;
        }
        goToStep(3);
    });
    
    $('#backToTemplate').on('click', function() {
        goToStep(2);
    });
    
    $('#nextToConfirm').on('click', function() {
        goToStep(4);
        updateConfirmation();
    });
    
    $('#backToProcess').on('click', function() {
        goToStep(3);
    });
    
    // 切换步骤
    function goToStep(step) {
        // 隐藏所有步骤内容
        $('.step-content').hide();
        
        // 更新步骤指示器
        $('.step').removeClass('active completed');
        for (let i = 1; i < step; i++) {
            $(`.step:nth-child(${i * 2 - 1})`).addClass('completed');
        }
        $(`.step:nth-child(${step * 2 - 1})`).addClass('active');
        
        // 显示当前步骤内容
        switch (step) {
            case 1:
                $('#upload-step').show();
                break;
            case 2:
                $('#template-step').show();
                break;
            case 3:
                $('#process-step').show();
                break;
            case 4:
                $('#confirm-step').show();
                break;
        }
        
        currentStep = step;
    }
    
    // 加载模板列表
    function loadTemplates() {
        $('#templateLoading').show();
        $('#templateList').empty();
        
        $.ajax({
            url: '/api/templates/',
            method: 'GET',
            data: {
                search: $('#templateSearch').val(),
                status: $('#templateFilter').val(),
                ordering: $('#templateSort').val()
            },
            success: function(data) {
                renderTemplates(data.results || data);
            },
            error: function() {
                showNotification('加载模板失败', 'error');
            },
            complete: function() {
                $('#templateLoading').hide();
            }
        });
    }
    
    // 渲染模板列表
    function renderTemplates(templates) {
        const templateList = $('#templateList');
        templateList.empty();
        
        if (templates.length === 0) {
            templateList.html('<div class="text-center text-muted py-4">没有找到匹配的模板</div>');
            return;
        }
        
        templates.forEach(template => {
            const templateCard = $(`
                <div class="template-card" data-template-id="${template.id}">
                    <div class="template-header">
                        <div class="template-name">${template.name}</div>
                        <span class="template-status ${template.is_active ? 'active' : 'inactive'}">
                            ${template.is_active ? '启用' : '禁用'}
                        </span>
                    </div>
                    <div class="template-description">${template.description || '暂无描述'}</div>
                    <div class="template-meta">
                        <span><i class="fas fa-file-alt me-1"></i>${template.file_type || '通用'}</span>
                        <span><i class="fas fa-download me-1"></i>${template.output_format ? template.output_format.toUpperCase() : 'EXCEL'}</span>
                        <span><i class="fas fa-clock me-1"></i>${formatDate(template.updated_at)}</span>
                    </div>
                </div>
            `);
            
            templateList.append(templateCard);
        });
    }
    
    // 模板选择
    $(document).on('click', '.template-card', function() {
        const templateId = $(this).data('template-id');
        
        // 移除其他选中状态
        $('.template-card').removeClass('selected');
        
        // 添加选中状态
        $(this).addClass('selected');
        
        // 保存选中的模板
        selectedTemplate = templateId;
        
        // 启用下一步按钮
        $('#nextToProcess').prop('disabled', false);
    });
    
    // 模板搜索和过滤
    $('#templateSearch, #templateFilter, #templateSort').on('change input', function() {
        loadTemplates();
    });
    
    // 更新确认信息
    function updateConfirmation() {
        // 文件信息
        const confirmFiles = $('#confirmFiles');
        confirmFiles.empty();
        uploadedFiles.forEach(file => {
            confirmFiles.append(`
                <div class="d-flex align-items-center mb-2">
                    <i class="fas ${getFileIcon(file.name)} me-2"></i>
                    <span>${file.name} (${formatFileSize(file.size)})</span>
                </div>
            `);
        });
        
        // 模板信息
        const confirmTemplate = $('#confirmTemplate');
        if (selectedTemplate) {
            const templateCard = $(`.template-card[data-template-id="${selectedTemplate}"]`);
            const templateName = templateCard.find('.template-name').text();
            const templateDesc = templateCard.find('.template-description').text();
            confirmTemplate.html(`
                <div class="mb-2">
                    <strong>${templateName}</strong>
                </div>
                <div class="text-muted">${templateDesc}</div>
            `);
        }
        
        // 配置信息
        const confirmConfig = $('#confirmConfig');
        const outputFormat = $('input[name="outputFormat"]:checked').val();
        const options = [];
        if ($('#removeEmptyRows').is(':checked')) options.push('移除空行');
        if ($('#trimWhitespace').is(':checked')) options.push('去除首尾空格');
        if ($('#validateData').is(':checked')) options.push('数据验证');
        
        confirmConfig.html(`
            <div class="row">
                <div class="col-md-6">
                    <strong>输出格式：</strong>${outputFormat.toUpperCase()}
                </div>
                <div class="col-md-6">
                    <strong>优先级：</strong>${$('#taskPriority option:selected').text()}
                </div>
            </div>
            <div class="mt-2">
                <strong>处理选项：</strong>${options.length > 0 ? options.join(', ') : '无'}
            </div>
            ${$('#taskDescription').val() ? '<div class="mt-2"><strong>描述：</strong>' + $('#taskDescription').val() + '</div>' : ''}
        `);
    }
    
    // 提交任务
    $('#submitTask').on('click', function() {
        const formData = new FormData();
        
        // 添加文件和文件配置信息
        const fileConfigs = [];
        uploadedFiles.forEach((file, index) => {
            formData.append('files', file);
            fileConfigs.push({
                index: index,
                source_name: file.sourceName || '',
                file_type: file.fileType || 'source',
                original_name: file.name
            });
        });
        
        // 添加文件配置信息
        formData.append('file_configs', JSON.stringify(fileConfigs));
        
        // 添加配置
        formData.append('template_id', selectedTemplate);
        formData.append('output_format', $('input[name="outputFormat"]:checked').val());
        formData.append('priority', $('#taskPriority').val());
        formData.append('description', $('#taskDescription').val());
        formData.append('remove_empty_rows', $('#removeEmptyRows').is(':checked'));
        formData.append('trim_whitespace', $('#trimWhitespace').is(':checked'));
        formData.append('validate_data', $('#validateData').is(':checked'));
        
        // 禁用提交按钮
        $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>提交中...');
        
        $.ajax({
            url: '/api/tasks/',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(data) {
                $('#taskId').text(data.id);
                $('#successModal').modal('show');
            },
            error: function(xhr) {
                const error = xhr.responseJSON?.detail || '提交失败';
                showNotification(error, 'error');
            },
            complete: function() {
                $('#submitTask').prop('disabled', false).html('<i class="fas fa-play me-1"></i> 提交任务');
            }
        });
    });
    
    // 创建新任务
    $('#createNewTask').on('click', function() {
        location.reload();
    });
    
    // 加载最近任务
    function loadRecentTasks() {
        $.ajax({
            url: '/api/tasks/',
            method: 'GET',
            data: {
                limit: 5,
                ordering: '-created_at'
            },
            success: function(data) {
                renderRecentTasks(data.results || data);
            },
            error: function() {
                $('#recentTasks').html('<div class="text-muted">加载失败</div>');
            }
        });
    }
    
    // 渲染最近任务
    function renderRecentTasks(tasks) {
        const recentTasks = $('#recentTasks');
        recentTasks.empty();
        
        if (tasks.length === 0) {
            recentTasks.html('<div class="text-muted">暂无任务</div>');
            return;
        }
        
        tasks.forEach(task => {
            const taskItem = $(`
                <div class="d-flex justify-content-between align-items-center mb-2 pb-2 border-bottom">
                    <div>
                        <div class="fw-bold">${task.description || '数据处理任务'}</div>
                        <small class="text-muted">${formatDate(task.created_at)}</small>
                    </div>
                    <span class="badge bg-${getStatusColor(task.status)}">${getStatusText(task.status)}</span>
                </div>
            `);
            
            recentTasks.append(taskItem);
        });
    }
    
    // 获取状态颜色
    function getStatusColor(status) {
        switch (status) {
            case 'pending': return 'secondary';
            case 'processing': return 'primary';
            case 'completed': return 'success';
            case 'failed': return 'danger';
            default: return 'secondary';
        }
    }
    
    // 获取状态文本
    function getStatusText(status) {
        switch (status) {
            case 'pending': return '等待中';
            case 'processing': return '处理中';
            case 'completed': return '已完成';
            case 'failed': return '失败';
            default: return '未知';
        }
    }
    
    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
    }
    
    // 显示通知
    function showNotification(message, type = 'info') {
        // 这里可以集成通知组件
        console.log(`${type}: ${message}`);
        showToast(message, type); // 使用现代化的Toast通知组件
    }
});
</script>
{% endblock %}